package com.ngo100.demo.service;

import com.ngo100.demo.dto.IdCardDTO;
import com.ngo100.demo.jna.IDCardInfo;
import com.ngo100.demo.jna.IDCardLibrary;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class IdCardService {
    private final IDCardLibrary library = IDCardLibrary.INSTANCE;

    // 读取身份证信息（基于文档中GetIDCardInfo方法）
    public IdCardDTO readIdCard() {
        // 1. 检查读卡器连接
        int deviceStatus = library.FindDevice();
        if (deviceStatus != 0) {
            throw new RuntimeException("读卡器未连接（错误码：" + deviceStatus + "）");
        }

        // 2. 寻卡
        int findCardResult = library.FindCard();
        if (findCardResult != 11) {
            throw new RuntimeException("未检测到卡片（错误码：" + findCardResult + "）");
        }

        // 3. 读取完整信息
        IDCardInfo cardInfo = new IDCardInfo();
        int readResult = library.GetIDCardInfo(cardInfo);
        if (readResult != 0) {
            throw new RuntimeException("读卡失败（错误码：" + readResult + "，原因：" + getErrorMsg(readResult) + "）");
        }
        // 4. 转换为DTO
        IdCardDTO dto = new IdCardDTO();
        dto.setName(parseBSTR(cardInfo.Name));
        dto.setGender(parseBSTR(cardInfo.Gender));
        dto.setNation(parseBSTR(cardInfo.Nation));
        dto.setBirthDate(parseBSTR(cardInfo.BirthDate));
        dto.setAddress(parseBSTR(cardInfo.Address));
        dto.setIdCardNo(parseBSTR(cardInfo.IDCardNo));
        dto.setGrantDept(parseBSTR(cardInfo.GrantDept));
        dto.setEffDate(cleanDate(parseBSTR(cardInfo.EffDate))); // 清洗有效期
        dto.setExpDate(cleanDate(parseBSTR(cardInfo.ExpDate)));

        dto.setPhotoBase64(new String(cardInfo.ImgBase64, StandardCharsets.ISO_8859_1).trim());
        return dto;
    }

    private String parseBSTR(byte[] bstrBytes) {
        int endIndex = bstrBytes.length;
        try {
            while (endIndex > 0 && bstrBytes[endIndex - 1] == 0) {
                endIndex--;
            }
            String value = new String(bstrBytes, 0, endIndex, "GBK").trim();
            return value.replace("\u0000", ""); // 关键：去除所有空字符
        } catch (Exception e) {
            try {
                String value = new String(bstrBytes, 0, endIndex, "GB2312").trim();
                return value.replace("\u0000", "");
            } catch (Exception ex) {
                return "";
            }
        }
    }

    // 清洗有效期为8位数字（yyyyMMdd）
    private String cleanDate(String dateStr) {
        if (dateStr == null) return "";
        String numeric = dateStr.replaceAll("[^0-9]", ""); // 保留数字
        return numeric.length() >= 8 ? numeric.substring(0, 8) : numeric;
    }

    // 错误码转换（文档中读卡错误码）
    private String getErrorMsg(int errorCode) {
        switch (errorCode) {
            case 1:
                return "没有找到读卡器";
            case 2:
                return "开启读卡器失败";
            case 3:
                return "关闭读卡器失败";
            case 4:
                return "识别不到身份证";
            case 5:
                return "读取身份证信息失败";
            case 6:
                return "回写身份证图片到本地失败";
            case 7:
                return "保存bmp文件失败";
            case 8:
                return "转化jpg文件失败";
            case 9:
                return "获取SAMID失败";
            case 99:
                return "其他错误";
            default:
                return "未知错误";
        }
    }
}
